const express = require("express");
const accessRouter = express.Router();
const DB = require("./../db/config");
module.exports = accessRouter;

/**
 * 获取所有权限
 * 查询权限
 */
accessRouter.route("/access/getAccess").get((req, res) => {
  let { searchText } = req.query;

  let sql = searchText
    ? "select * from permissions where pname like ?;"
    : "select * from permissions;";
  let param = [];

  searchText && param.push("%" + searchText + "%");

  let cb = (err, data) => {
    if (!err) {
      res.json({ code: 0, msg: "获取所有权限成功", data });
    } else {
      res.json({ code: 4002, msg: "获取所有权限失败", data });
    }
  };
  DB.connect(sql, param, cb);
});
/**
 * 添加权限
 * @param {String} accessName
 * @param {String} accessDes
 *
 */
accessRouter.route("/access/addAccess").post((req, res) => {
  let { accessName, accessDes } = req.body;
  let sql = "insert into permissions (pname, pdes) values (?,?);";
  let params = [accessName, accessDes];
  let cb = (err, data) => {
    console.log(err);
    if (err === null) {
      res.json({ code: 0, msg: "添加权限成功", data });
    } else {
      res.json({ code: 4002, msg: "添加权限失败", data });
    }
  };
  DB.connect(sql, params, cb);
});

/**
 * 删除一个权限
 */
accessRouter.route("/access/delAccess").post((req, res) => {
  let { acid } = req.body;
  let sql = "delete from permissions where pid = ?;";
  let cb = (err, data) => {
	  console.log(err)
    if (!err) {
      res.json({ code: 0, msg: "删除权限成功", data });
    } else {
      res.json({ code: 4002, msg: "删除权限失败", data });
    }
  };
  DB.connect(sql, [acid], cb);
});

/*
 * 获取一个权限的已授权角色的数据
 */
accessRouter.route("/access/getRoleForAccess").get((req, res) => {
  let { AccessIdForRole } = req.query;
  let sql =
    "select * from permissions as p join rolepermissinstable as rpt on p.pid = rpt.pid join roles as r on r.rid = rpt.rid where p.pid = ?;";
  let param = [AccessIdForRole];
  let cb = (err, data) => {
    console.log(err);
    if (!err) {
      res.json({
        code: 0,
        msg: "获取一个权限的已授权角色的数据 ，查询成功",
        data,
      });
    } else {
      res.json({
        code: 0,
        msg: "获取一个权限的已授权角色的数据 ，查询失败",
        data,
      });
    }
  };
  DB.connect(sql, param, cb);
});
/**
 * 批量添加（授权）角色
 */
accessRouter.route("/access/addAccessToRole").post((req, res) => {
  let { AccessIdForRole, roleSelectedId } = req.body;
  console.log(req.body);
  new Promise((resolve, reject) => {
    let sql = "delete from rolepermissinstable where pid = ?;";
    let param = [AccessIdForRole];
    let cb = (err, data) => {
      if (!err) {
        // res.json({code: 0, msg:'删除权限授权的角色成功',data})
        resolve("删除权限授权的角色成功");
      } else {
        // res.json({code: 4002, msg:'删除权限授权的角色失败',data})
        reject("删除权限授权的角色失败");
      }
    };
    DB.connect(sql, param, cb);
  })
    .then((data) => {
      return new Promise((resolve, reject) => {
        let params = [];
        let temp = [];

        if (roleSelectedId === undefined) {
          // console.log("!");
          resolve("取消批量授权角色成功");

        } else {
          // console.log("!!");
          roleSelectedId.forEach((el) => {
            temp.push("(?,?)");
            params.push(el, AccessIdForRole);
          });
          let sql = "insert into rolepermissinstable (rid,pid) values";
          sql = sql + temp.join(",");
          //  console.log(sql);
          //  console.log(params);
          let cb = (err, data) => {
            console.log(err);
            if (err === null) {
              resolve("批量授权角色成功");
            } else {
              reject("给角色设批量授权角色失败置用户失败。");
            }
          };
          DB.connect(sql, params, cb);
        }
      });
    })
    .then((dataMsg) => {
      res.json({ code: 0, msg: dataMsg, data: [] });
    })
    .catch((errmsg) => {
      res.json({ code: 4002, msg: errmsg });
    });
});
